home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5734 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  59 lines

  1. Path: nntp208.reach.com!usenet
  2. From: Cliff Vick <cvick@reach.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Visibility Restricted to Compiler
  5. Date: Tue, 06 Feb 1996 11:34:01 -0500
  6. Organization: Reach Networks
  7. Message-ID: <311782F9.17C3@reach.com>
  8. References: <4eq8td$hpu@vixen.cso.uiuc.edu> <4ettcg$d1f@mastermind.odi.com>
  9. NNTP-Posting-Host: jmkpc.reach.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (Win95; I)
  14.  
  15. >If the constructor is private, it can only be called by the class 
  16. >itself.  It can't even be called implicitly by new.
  17.  
  18. Not true.  You can call the constructor by using new (as in the 
  19. following):
  20.  
  21. A good reason to want a private constructor is when you want to control 
  22. how many instantations of an object there are at run time.  For example, 
  23. say I want an object that is only instantiated once and once only, but 
  24. also providing access to this single object to everyone.  I could create 
  25. something like the following:
  26.  
  27. Declaration:
  28.  
  29. class SingleObject
  30. {
  31. public:
  32.     static SingleObject* Instance();
  33. private:
  34.     SingleObject();
  35.  
  36.     static SingleObject * instance;
  37. };
  38.  
  39.  
  40. Implementation:
  41.  
  42. SingleObject* SingleObject::instance = NULL;
  43.  
  44. SingleObject* SingleObject::Instance()
  45. {
  46.     if (instance == NULL)
  47.         instance = new SingleObject;
  48.     return instance;
  49. }
  50.  
  51.  
  52. The above is a simple view of achieving only one instance of a specific 
  53. class.  In practice, you might want to implement some kind of reference 
  54. counting mechanism so that you know how many 'things' are using this 
  55. instance, then when you are ready to get rid of the single object, you 
  56. can safely destruct only when no one is using it.
  57.  
  58. cliffv@reach.com
  59.